/*
 * @Author: fhw
 * @Date: 2022-07-28 16:13:15
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-11-18 14:42:29
 * @Description:
 */
import { HttpException, HttpStatus, Injectable, UseFilters } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { isNil, isEmpty } from 'ramda'
import { Like, Repository } from 'typeorm'
import { HttpExceptionFilter } from '../http-exception.filter'
import { ArticleCategoryDto, UpdateCategoryDto, CreateCategoryDto } from './dto/article_category.dto'
import { CategoryResult, Category } from './entities/article_category.entity'
import { IdDto } from '../common/dto/dto'
import { throwHttp } from 'src/utlis'
@Injectable()
export class ArticleCategoryService {
  constructor(
    @InjectRepository(Category)
    private articleCategoryRepository: Repository<Category>,
  ) {}
  // 获取文章分类
  @UseFilters(new HttpExceptionFilter())
  async getArticleCategory(params: ArticleCategoryDto): Promise<CategoryResult> {
    try {
      const pageSize = Number(params.pageSize) || 10
      let { pageNum = 0 } = params
      if (pageNum !== 0) {
        pageNum -= 1
      }
      const [data, total] = await this.articleCategoryRepository.findAndCount({
        where: {
          name: Like(`%${params.name ?? ''}%`),
        },
        skip: pageNum * pageSize,
        take: pageSize,
        cache: true,
      })
      return {
        data,
        total,
        pageSize,
        pageNum: pageNum * pageSize + 1,
      }
    } catch (error) {
      throwHttp(error.message)
    }
  }
  // 获取分类详情
  @UseFilters(new HttpExceptionFilter())
  async getCategoryInfo({ id }: IdDto): Promise<{ data: Category }> {
    try {
      const data = await this.articleCategoryRepository.findOne({
        where: { id },
      })
      if (isNil(data) || isEmpty(data)) {
        throwHttp('分类不存在，请检查id是否正确')
      }
      return {
        data,
      }
    } catch (error) {
      throwHttp(error.message)
    }
  }
  // 创建分类
  @UseFilters(new HttpExceptionFilter())
  async createCategory({ name }: CreateCategoryDto) {
    try {
      const data = await this.articleCategoryRepository.findOne({
        where: { name },
      })
      if (!isNil(data)) {
        throwHttp( '分类已存在')
      }
      const category = new Category()
      category.name = name
      const result = await this.articleCategoryRepository.manager.save(category)
      return !isEmpty(result) ? `创建 ${result.name} 成功` : '创建失败'
    } catch (error) {
      throwHttp(error.message)
    }
  }
  // 更新分类
  @UseFilters(new HttpExceptionFilter())
  async updateCategory({ id, name }: UpdateCategoryDto): Promise<string> {
    try {
      await this.getCategoryInfo({ id })
      const { affected } = await this.articleCategoryRepository
        .createQueryBuilder()
        .update('article_category')
        .set({ name })
        .where('id = :id', { id })
        .execute()
      if (affected) {
        return '更新成功'
      }
      throwHttp('更新分类失败')
    } catch (error) {
      throwHttp(error.message)
    }
  }
  // 删除分类
  @UseFilters(new HttpExceptionFilter())
  async delCategory({ id }: IdDto) {
    try {
      const { data } = await this.getCategoryInfo({ id })
      await this.articleCategoryRepository.remove(data)
      return `删除成功`
    } catch (error) {
      throwHttp(error.message)
    }
  }
}
